﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using StaticView.Resources;
using System.Threading;

namespace StaticView
{
    public partial class MainPage : PhoneApplicationPage
    {
        Thread updateThread;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Initialize
            updateThread = new Thread(new ThreadStart(Position.Update));

            // Check sensors (test project only)
            t_result.Text += "Accelerometer: ";
            if (Microsoft.Devices.Sensors.Accelerometer.IsSupported) t_result.Text += "Support";
            else t_result.Text += "Unsupport";

            t_result.Text += "\nGyroscope: ";
            if (Microsoft.Devices.Sensors.Gyroscope.IsSupported) t_result.Text += "Support";
            else t_result.Text += "Unsupport";

            t_result.Text += "\nMagnetometer: ";
            if (Microsoft.Devices.Sensors.Compass.IsSupported) t_result.Text += "Support";
            else t_result.Text += "Unsupport";

            // Calibrating
            t_status.Text = "Calibrating...";
            Position.Calibrate(CalibrationCallback);
        }

        // Call after preparation thread is finished
        public void CalibrationCallback(float gravity, string noise, string grav)
        {
            // Run update thread, cross-thread call
            Dispatcher.BeginInvoke(() =>
            {
                t_status.Text = "Ready";
                b_viewer.IsEnabled = true;
                // Test only
                t_result.Text += "\nGravity: " + gravity + "\n" + grav;
                t_result.Text += "\nNoise: \n" + noise;
                // ----------------------------------------
                updateThread.Start();
            });
        }

        private void b_viewer_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Viewer.xaml", UriKind.Relative));
        }
    }
}